<template>
    <view class="content">
		<view class="info">
			
		</view>
        <view class="oauth-row" v-if="hasProvider" v-bind:style="{top: positionTop + 'px'}">
            <view v-for="provider in providerList" :key="provider.value">
				<button class="oauth-button" open-type="getUserInfo" @getuserinfo="onGotUserInfo" >进入账本</button>
            </view>
        </view>
    </view>
</template>

<script>
    import service from '../../service.js';
    import {
        mapState,
        mapMutations
    } from 'vuex'
    import mInput from '../../components/m-input.vue'
	import * as api from '../../api/api.js'

    export default {
        components: {
            mInput
        },
        data() {
            return {
                providerList: [],
                hasProvider: false,
                positionTop: 0
            }
        },
        computed: mapState(['forcedLogin', 'openid', 'sessionKey']),
        methods: {
            ...mapMutations(['login', 'store']),
            initProvider() {
                const filters = ['weixin'];
                uni.getProvider({
                    service: 'oauth',
                    success: (res) => {
                        if (res.provider && res.provider.length) {
                            for (let i = 0; i < res.provider.length; i++) {
                                if (~filters.indexOf(res.provider[i])) {
                                    this.providerList.push({
                                        value: res.provider[i],
                                        image: '../../static/img/' + res.provider[i] + '.png'
                                    });
                                }
                            }
                            this.hasProvider = true;
                        }
                    },
                    fail: (err) => {
                        console.error('获取服务供应商失败：' + JSON.stringify(err));
                    }
                });
            },
            initPosition() {
                /**
                 * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
                 * 反向使用 top 进行定位，可以避免此问题。
                 */
                this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
            },
			onGotUserInfo(e) {
				console.log(e)
				this.toMain(e.detail.userInfo);
				this.oauth('weixin');
				
				this.login({
					"nickName": uni.getStorageSync("ysjz_userName"),
					"avatarUrl": uni.getStorageSync("ysjz_avatarUrl"),
					"openid": uni.getStorageSync("ysjz_openid"),
					"sessionKey": uni.getStorageSync("ysjz_session_key")
				});
				
				const userInfo = e.detail.userInfo;
				userInfo.openId = this.openid;
				userInfo.sessionKey = this.sessionKey;
				api.wxLogin(JSON.stringify(userInfo))
			},
            oauth(value) {
                uni.login({
                    provider: value,
                    success: (res) => {
						uni.request({
							url: "https://api.weixin.qq.com/sns/jscode2session?appid=wxeb7a5c3c7e80e72b&secret=6cd7fefbb44f13bfede45c765831a3dc&js_code=" + res.code +"&grant_type=authorization_code",
							success: (res) => {
								uni.setStorage({
									key: "ysjz_openid",
									data: res.data.openid
								})
								uni.setStorage({
									key: "ysjz_session_key",
									data: res.data.session_key
								})
							}
						})
                    },
                    fail: (err) => {
                        console.error('授权登录失败：' + JSON.stringify(err));
                    }
                });
            },
            toMain(user) {
                uni.setStorage({
                	key: "ysjz_userName",
                	data: user.nickName || '新用户'
                })
                uni.setStorage({
                	key: "ysjz_avatarUrl",
                	data: user.avatarUrl
                })
                uni.setStorage({
                	key: "ysjz_hasLogin",
                	data: true
                })
				
                /**
                 * 强制登录时使用reLaunch方式跳转过来
                 * 返回首页也使用reLaunch方式
                 */
                if (this.forcedLogin) {
                    uni.reLaunch({
                        url: '../main/main',
                    });
                } else {
                    uni.navigateBack();
                }

            }
        },
        onReady() {
            this.initPosition();
            this.initProvider();
        }
    }
</script>

<style>
    .action-row {
        display: flex;
        flex-direction: row;
        justify-content: center;
    }

    .action-row navigator {
        color: #007aff;
        padding: 0 20upx;
    }

    .oauth-row {
        display: flex;
        flex-direction: row;
        justify-content: center;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
    }

    /* .oauth-image {
        width: 100upx;
        height: 100upx;
        border: 1upx solid #dddddd;
        border-radius: 100upx;
        margin: 0 40upx;
        background-color: #ffffff;
    }

    .oauth-image image {
        width: 60upx;
        height: 60upx;
        margin: 20upx;
    } */
	.info{
		/* 存放个人信息的 */
		width: calc( 100% - 32px );
		background-color: #FFFFFF;
		margin-left: 16px;
		margin-top: -48px;
		float: left;
		border-radius: 8px;
		box-shadow: 0 0 6px rgba(255,218,25,0.6);
	}
	
	.oauth-button {
	    width: 500upx;
	    height: 90upx;
	    margin: 20upx;
		background-color: #FFDA19;
		font-family: "NSimSun";
		border-radius: 30upx;
		box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
	}
</style>
